package com.helper.extens

import android.app.Activity

import android.content.Intent
import android.os.Bundle

import android.util.Log
import android.widget.Toast
import androidx.annotation.ColorRes
import androidx.annotation.DimenRes
import androidx.core.content.ContextCompat
import com.google.gson.Gson

import com.helper.Constants
import com.helper.utils.ToastUtil
import com.sh.doctors.cloud.BuildConfig
import java.math.BigDecimal
import java.math.RoundingMode
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException


/**
 * description：some extens
 *
 * Created by ditclear on 2017/9/29.
 */

fun Activity.getCompactColor(@ColorRes colorRes: Int): Int = ContextCompat.getColor(this, colorRes)

fun Activity.dpToPx(@DimenRes resID: Int): Int = this.resources.getDimensionPixelOffset(resID)

fun Any.logD(msg: String?) {
    if (BuildConfig.DEBUG) {
        Log.d(javaClass.simpleName, msg)
    }
}

fun Activity.toast(msg: CharSequence, duration: Int = Toast.LENGTH_SHORT, type: Int = Constants.NORMAL) {
    when (type) {
        Constants.WARNING -> ToastUtil.warning(this, msg, duration)
        Constants.ERROR -> ToastUtil.error(this, msg, duration)
        Constants.NORMAL -> ToastUtil.info(this, msg, duration)
        Constants.SUCCESS -> ToastUtil.success(this, msg, duration)
    }
}

fun parseError(error: Throwable?): String {
    var msg = ""
    error?.let {
        if (error is SocketTimeoutException) {
            msg = "网络连接超时"

        } else if (it is UnknownHostException || it is ConnectException) {
            msg = "网络未连接"

        } else {
            msg = it.message ?: ""
        }
    }
    return msg
}

fun Activity.dispatchFailure(error: Throwable?) {
    error?.let {
        if (BuildConfig.DEBUG) {
            it.printStackTrace()
        }
        if (error is SocketTimeoutException) {
            it.message?.let { toast("网络连接超时", Constants.ERROR) }

        } else if (it is UnknownHostException || it is ConnectException) {
            //网络未连接
            it.message?.let { toast("网络未连接", Constants.ERROR) }

        } else {
            it.message?.let { toast(it, Constants.ERROR) }
        }
    }
}

fun Activity.navigateTo(cls: Class<*>, bundle: Bundle? = null) {
    startActivity(Intent(this, cls).apply {
        bundle?.let {
            putExtras(bundle)
        }

    })
}

/////////////////////////////////////Json///////////////////////////////////////
//转换obj to json String
fun Any.toJson(): String = Gson().toJson(this)


fun <J> String.toObj(c: Class<J>): J? = Gson().fromJson(this, c) as J


fun BigDecimal.toAmount(): String = setScale(2, RoundingMode.HALF_UP).toString()

fun BigDecimal.toWeight(bit: Int = 2): String {
    return if (compareTo(BigDecimal(toInt())) == 0) {
        toInt().toString()
    } else {
        setScale(bit, RoundingMode.HALF_UP).toString()
    }
}